package com.example.skycode5.servlet;

import com.example.skycode5.bean.NewsBean;
import com.example.skycode5.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/news")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String p = req.getParameter("page");// 获取用户传递来的代码
        int page = 1;//默认页码1
        if (p != null && p.equals("")) {
            page = Integer.parseInt(p);//字符串转整数
        }
        // 1.获取新闻信息
        NewsDao newsDao = new NewsDao();
        List<NewsBean> news = newsDao.getList(page);
        //给用户总条数 当前页数 总页数 上一页 下一页
        int totalCount,curPage,totalPage,upPage,downPage;
        totalCount = newsDao.count();//总条数
        curPage = page;//用户传进来的页码
        if (totalCount%10 == 0){//
            totalPage = totalCount/10;
        }else {
            totalPage = totalCount/10+1;//计算总页数
        }
        // 上一页 当前页数减去1
        if (curPage==1){
            upPage = 1;
        }else {
            upPage = curPage-1;
        }
        if (curPage==totalPage){//当前页数等于总页数相同下一页不+1
            downPage = totalPage;
        }else {
            downPage = curPage+1;
        }
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("curPage", curPage);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("upPage", upPage);
        req.setAttribute("downPage", downPage);
        // 2.传递新闻信息给前端页面
        req.setAttribute("news",news);
        // 3.加载显示前端页面
        req.getRequestDispatcher("WEB-INF/news.jsp").forward(req,resp);
    }
}
